package com.tiancheng.trade.order.util;

import com.tiancheng.trade.commom.core.exception.BusinessException;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.enums.OrderPayStatusEnum;
import com.tiancheng.trade.order.enums.OrderSourceEnum;
import com.tiancheng.trade.order.enums.OrderStatusEnum;
import com.tiancheng.trade.order.vo.app.res.CashierResVO;
import com.tiancheng.trade.order.vo.app.res.OrderPrePayResVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单系统，java、php两套并行时的兼容处理
 *
 * @author kellen
 * @date 2024/5/31
 */
@Slf4j
public final class OrderParallelUtil {

    /**
     * 根据业务来源定义描述
     * @param orderSource
     * @param tradeInfo
     * @return
     */
    public static String getBatchDesc(OrderSourceEnum orderSource, String tradeInfo) {
        Map<String, Object> tradeInfoMap = JsonUtil.fromJson(tradeInfo, Map.class);
        if(null==tradeInfoMap){
            return "";
        }
        StringBuilder batchDesc = new StringBuilder();
        /*switch (orderSource) {
            case FLIGHT:
            case TICKET:
                batchDesc.append("共").append(tradeInfoMap.get("nums")).append("张");
                break;
            case HOTEL:
                batchDesc.append("共").append(tradeInfoMap.get("nums_of_night")).append("晚");
                break;
            case LINE:
                batchDesc.append("共").append(tradeInfoMap.get("nums")).append("人");
                break;
            case CHARTERE:
                LocalDate chartererStartTime = DateTimeUtil.formatDate(String.valueOf(tradeInfoMap.get("arrv_date")), "yyyy-MM-dd");
                LocalDate chartererEndTime = DateTimeUtil.formatDate(String.valueOf(tradeInfoMap.get("dept_date")), "yyyy-MM-dd");
                long diffDay = Period.between(chartererStartTime, chartererEndTime).getDays();
                batchDesc.append("共").append(diffDay + 1).append("天");
                break;
            case TRAFFIC:
                if(!tradeInfoMap.containsKey("arrv_date" )||!tradeInfoMap.containsKey("arrv_time")||!tradeInfoMap.containsKey("dept_date")
                        ||!tradeInfoMap.containsKey("dept_time")){
                    break;
                }
                StringBuilder startTimeStr = new StringBuilder(String.valueOf(tradeInfoMap.get("arrv_date"))).append(tradeInfoMap.get("arrv_time"));
                StringBuilder endTimeStr = new StringBuilder(String.valueOf(tradeInfoMap.get("dept_date"))).append(tradeInfoMap.get("dept_time"));
                LocalDateTime startTime = DateTimeUtil.format(startTimeStr.toString(), "yyyy-MM-ddHH:mm");
                LocalDateTime endTime = DateTimeUtil.format(endTimeStr.toString(), "yyyy-MM-ddHH:mm");
                long diff = Duration.between(startTime, endTime).toMinutes();
                batchDesc.append("共");
                if((diff / 1440) >= 1) {
                    batchDesc.append(diff/1440).append("天");
                } else if((diff / 60) >= 1) {
                    batchDesc.append(diff/60).append("小时");
                } else {
                    batchDesc.append(diff).append("分钟");
                }
                break;
            case BUS_TICKET:
                batchDesc.append("共").append(tradeInfoMap.get("nums")).append("人");
                break;
            case TOURISM_PACKAGES:
                batchDesc.append("购买数量").append(tradeInfoMap.get("nums")).append("份");
                break;
        }*/
        return batchDesc.toString();
    }

    /**
     * 转换成旧系统的状态查询条件
     * @param status
     * @return
     */
    public static String getStatus(String status) {
        if(status.equals(OrderStatusEnum.paid.getCode())) {
            return "pay_success";
        } else if (status.equals(OrderStatusEnum.waiting_pay.getCode())) {
            return "WP";
        } else {
            return null;
        }
    }

    /**
     * 根据业务类型设置数据
     * @param obj
     * @param clz
     * @param orderSourceEnum
     * @param tradeInfo
     */
    public static void setTradeInfo(Object obj, Class clz, OrderSourceEnum orderSourceEnum, Object tradeInfo) {
        try {
            String methodName = new StringBuilder("set").append(StringUtils.capitalize(
                    CommonUtil.underlineToHump(orderSourceEnum.name().toLowerCase()))).append("Info").toString();
            Method method = clz.getMethod(methodName, Object.class);
            method.invoke(obj, tradeInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 根据订单号，判断是否调用老的订单中心系统
     * @param orderId
     * @return
     */
    public static boolean isOrderSubSystem(String orderId) {
//        String orderSource = orderId.substring(0, 1);
        // 目前门票业务来源是走新系统
        if (orderId.startsWith("B") || orderId.length() >= 17) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 转换成新系统的收银台出参
     * @param dataMap
     * @return
     */
    public static CashierResVO transToCashierRes(Map<String, Object> dataMap) throws BusinessException {
        if(dataMap.containsKey("is_can_pay") && "0".equals(String.valueOf(dataMap.get("is_can_pay")))) {
            BusinessErrorInfoEnum.OLD_ORDER_CAN_NOT_PAY.assertFail();
        }

        CashierResVO resVO = new CashierResVO();
        resVO.setOrderName(String.valueOf(dataMap.get("order_name")));
        resVO.setOrderAmount(new BigDecimal(String.valueOf(dataMap.get("pay_amount_yuan"))));
        resVO.setPayAmount(resVO.getOrderAmount());
        resVO.setPayLeftTime(Long.valueOf(String.valueOf(dataMap.get("pay_left_second"))));
        resVO.setDiscount(BigDecimal.ZERO);

        List<CashierResVO.Channel> channels = new ArrayList<>();
        List<Map<String, Object>> channelList = (List<Map<String, Object>>) dataMap.get("channels");
        channelList.forEach(channelMap -> {
            CashierResVO.Channel channel = new CashierResVO.Channel();
            channel.setChannelCode(String.valueOf(channelMap.get("channel_code")));
            channel.setChannelLabel(String.valueOf(channelMap.get("channel_label")));
            channel.setChannelIcon(String.valueOf(channelMap.get("channel_icon")));
            channel.setChannelSubtitle(String.valueOf(channelMap.get("channel_subtitle")));
            channels.add(channel);
        });
        resVO.setChannels(channels);

        CashierResVO.Order order = new CashierResVO.Order();
        order.setOrderId(String.valueOf(dataMap.get("order_id")));
        order.setOrderName(resVO.getOrderName());
        order.setOrderAmount(resVO.getOrderAmount());
        order.setPayAmount(resVO.getPayAmount());
        resVO.getOrders().add(order);

        return resVO;
    }

    /**
     * 转换成新系统的支付出参
     * @param dataMap
     * @return
     */
    public static OrderPrePayResVO transToOrderPrePayRes(Map<String, Object> dataMap) throws BusinessException {
        if(dataMap.containsKey("is_can_pay") && "0".equals(String.valueOf(dataMap.get("is_can_pay")))) {
            BusinessErrorInfoEnum.OLD_ORDER_CAN_NOT_PAY.assertFail();
        }

        OrderPrePayResVO resVO = new OrderPrePayResVO();
        resVO.setOrderName(String.valueOf(dataMap.get("goods_name")));
        resVO.setPayAmount(new BigDecimal(String.valueOf(dataMap.get("pay_amount_yuan"))));
        resVO.setOrderAmount(resVO.getPayAmount());
        resVO.setDiscount(BigDecimal.ZERO);
        resVO.setPayLeftTime(Long.valueOf(String.valueOf(dataMap.get("pay_left_second"))));

        Map<String, Object> payInfoMap = (Map<String, Object>) dataMap.get("payment_info");
        resVO.setPayInfo(String.valueOf(payInfoMap.get("pay_info")));

        OrderPrePayResVO.Order order = new OrderPrePayResVO.Order();
        order.setOrderId(String.valueOf(dataMap.get("order_id")));
        order.setOrderName(resVO.getOrderName());
        order.setOrderAmount(resVO.getOrderAmount());
        order.setPayAmount(resVO.getPayAmount());
        order.setOrderSource(String.valueOf(dataMap.get("type")));
        resVO.getOrders().add(order);

        return resVO;
    }

    /**
     * 转换成新系统的支付状态
     * @param status
     * @return
     */
    public static String transToPayStatus(String status) {
        if("pay_success".equals(status)) {
            return OrderPayStatusEnum.paid.code();
        } else {
            return OrderPayStatusEnum.un_pay.code();
        }
    }

    /**
     * 判断是否需要查询老系统信用授权信息
     * @param compatible 是否兼容老系统请求：Y-是，N—否，如果空或者Y，会再次查询老系统订单
     * @return
     */
    public static boolean needCompatible(String compatible) {
        return StringUtils.isEmpty(compatible) || compatible.toUpperCase().equals("Y");
    }
}
